package com.zu.commu.remote.process;

import com.zu.commu.context.Config;
import com.zu.commu.exception.CommuException;
import com.zu.commu.interf.Action;
import com.zu.commu.interf.Data;
import com.zu.commu.interf.Order;
import com.zu.commu.interf.gprs.Engine;
import com.zu.commu.interf.gprs.Handle;
import com.zu.commu.remote.session.Session;
import com.zu.commu.saveData.DataQueue;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class GprsProcess {
	private static Logger log = Logger.getLogger("com.automic.commu.remote.process.GprsProcess");
	private Session se;

	public GprsProcess(Session se) {
		this.se = se;
	}

	public void analyseData(int threadNum, byte[] s) {
		Handle handle = getHandle();

		if (handle == null) {
			log.error("出错，没有得到解析GPRS协议的实例！");
			return;
		}
		String gprsId = (String) this.se.getAttribute("gprsId");
		Action action = handle.analyseData(s, gprsId);

		if (action.equals(Action.SENDCENTER)) {
			byte[] data = handle.getCenterData();
			new MeterProcess(this.se).processData(threadNum, data);
		} else if (action.equals(Action.SENDREMOTE)) {
			byte[] buf = handle.getRemoteData();
			sendRemote(buf);
		} else if (action.equals(Action.SENDREMOTEANDCENTER)) {
			log.debug("发送控制器信号并将数据上传到业务处理层！");
			byte[] buf = handle.getRemoteData();
			sendRemote(buf);
			byte[] data = handle.getCenterData();

			new MeterProcess(this.se).processData(threadNum, data);
		} else if (action.equals(Action.SKIPNEXTPROCESS)) {
			Data[] data = handle.getDirectData();
			Order order = handle.dataFromwhatOrder();
			log.info("GPRS自身相关的数据，直接远端存储。");
			if ((data != null) && (data.length > 0))
				sendCenter(data, order);
		} else if (action.equals(Action.CANCELGPRS)) {
			byte[] buf = handle.getRemoteData();
			sendRemote(buf);
			this.se.close();
		} else if (action.equals(Action.NOACTION)) {
			log.info("没有动作。");
		} else if (action.equals(Action.ERROR)) {
			log.error(handle.getError());
		}
	}

	private void sendRemote(byte[] buf) {
		try {
			this.se.write(buf);
			if (Level.INFO.isGreaterOrEqual(log.getEffectiveLevel()))
				try {
					String hex = byte2Hex(buf);
					log.info("向远端GPRSID:" + this.se.getAttribute("gprsId") + "发送命令：" + hex);
				} catch (Exception e) {
					e.printStackTrace();
				}
		} catch (Exception e) {
			log.error("向远端发送数据出错 。", e);
		}
	}

	private String byte2Hex(byte[] b) throws CommuException {
		String rString = "";
		String temp = "";
		try {
			for (int i = 0; i < b.length; i++) {
				int c = b[i];
				temp = Integer.toHexString(c & 0xFF);
				if (temp.length() == 1) {
					temp = "0" + temp;
				}
				rString = rString + temp;
			}
		} catch (Exception e) {
			throw new CommuException().setMessage("字节数组转换成十六进制的字符串出错！", null);
		}
		return rString;
	}

	private Handle getHandle() {
		String gprsId = (String) this.se.getAttribute("gprsId");
		Config cf = Config.instance();
		String protocol = cf.getGPRSProcotolOfGPRSID(gprsId);
		if (protocol == null) {
			log.error("没有得到号码为" + gprsId + "的GPRS的通信协议。可能配置的sim卡号与实际的不相附合。");
			return null;
		}
		Engine engine = cf.getDriverOfGPRSProtocol(protocol);
		return engine.getHandle();
	}

	private void sendCenter(Data[] data, Order order) {
		String[] commandIds = this.se.putOutCommandId(order);
		Data temp = null;

		if (commandIds == null) {
			for (int i = 0; i < data.length; i++) {
				data[i].setGprsId((String) this.se.getAttribute("gprsId"));
				DataQueue dq = DataQueue.instance();
				if (order.equals(Order.CALL)) {
					dq.setDataToSecondQueue(data[i]);
				} else {
					log.error("数据是命令结果，但找不到这个命令的ID（可能是等待超时，命令ID被清除），丢弃此结果数据！");
				}
			}
		} else
			for (int j = 0; j < commandIds.length; j++)
				for (int i = 0; i < data.length; i++) {
					temp = data[i];
					temp.setGprsId((String) this.se.getAttribute("gprsId"));
					temp.setCommandId(commandIds[j]);
					DataQueue dq = DataQueue.instance();

					dq.setDataToFirstQueue(temp);
				}
	}
}